import axios from 'axios';

class ConfigService {
  constructor() {
    this.config = null;
    this.defaultConfig = {
      api_base_url: 'http://localhost:5000/api',
      max_file_size: 50 * 1024 * 1024, // 50MB
      allowed_extensions: ['docx', 'md', 'pdf'],
      supported_formats: [
        { value: 'docx', label: 'Word文档', icon: '📄' },
        { value: 'md', label: 'Markdown', icon: '📝' },
        { value: 'pdf', label: 'PDF文档', icon: '📋' }
      ],
      conversion_matrix: {
        'docx': ['md', 'pdf'],
        'md': ['docx', 'pdf'],
        'pdf': ['docx', 'md']
      }
    };
  }

  async loadConfig() {
    try {
      // 首先尝试从环境变量或当前位置获取配置
      const baseUrl = this.getInitialApiBaseUrl();
      const response = await axios.get(`${baseUrl}/config`, {
        timeout: 5000 // 5秒超时
      });
      this.config = response.data;
      return this.config;
    } catch (error) {
      console.warn('无法从服务器获取配置，使用默认配置:', error.message);
      // 使用默认配置
      this.config = { ...this.defaultConfig };
      this.config.api_base_url = this.getInitialApiBaseUrl();
      return this.config;
    }
  }

  getInitialApiBaseUrl() {
    // 从环境变量或当前主机动态构建API URL
    if (typeof window !== 'undefined') {
      const protocol = window.location.protocol;
      const hostname = window.location.hostname;
      
      // 尝试从不同的环境变量获取端口
      const port = process.env.VITE_API_PORT || 
                   process.env.REACT_APP_API_PORT || 
                   '5000'; // 默认端口
      
      return `${protocol}//${hostname}:${port}/api`;
    }
    
    // 对于服务端渲染或测试环境
    const apiUrl = process.env.VITE_API_BASE_URL || 
                   process.env.REACT_APP_API_BASE_URL || 
                   'http://localhost:5000/api';
    
    return apiUrl;
  }

  getApiBaseUrl() {
    if (this.config) {
      return this.config.api_base_url;
    }
    return this.getInitialApiBaseUrl();
  }

  getMaxFileSize() {
    if (!this.config) {
      return this.defaultConfig.max_file_size;
    }
    return this.config.max_file_size;
  }

  getAllowedExtensions() {
    if (!this.config) {
      return this.defaultConfig.allowed_extensions;
    }
    return this.config.allowed_extensions;
  }

  getSupportedFormats() {
    if (!this.config) {
      return this.defaultConfig.supported_formats;
    }
    return this.config.supported_formats;
  }

  getConversionMatrix() {
    if (!this.config) {
      return this.defaultConfig.conversion_matrix;
    }
    return this.config.conversion_matrix;
  }

  getAvailableTargetFormats(sourceFormat) {
    const matrix = this.getConversionMatrix();
    return matrix[sourceFormat] || [];
  }

  isFormatSupported(format) {
    return this.getAllowedExtensions().includes(format);
  }

  formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  }

  getMaxFileSizeFormatted() {
    return this.formatFileSize(this.getMaxFileSize());
  }
}

// 导出单例实例
export const configService = new ConfigService(); 